<?php

namespace app\admin\controller\extend;
use app\common\controller\Backend;
use think\Db;
use think\Loader;

/**
 * 运营管理
 *
 * @icon fa fa-file-text-o
 */
class Operation extends Backend
{
    /**
     * School模型对象
     */
    protected $searchFields = 'id';
    protected $model = null;
    protected $isSuperAdmin = false;
    protected $noNeedRight = ['change_status','module_name','get_url','hot_article','get_code','get_code2', 'post','hot_today','module_data_daily','do_icon','module_today_list','module_date_clicks','update_access_token'];
//    protected $noNeedLogin = ['update_flag'];


    public function _initialize()
    {
        parent::_initialize();
//        $this->model = new \app\admin\model\extend\Operation();
        //是否超级管理员
        $this->isSuperAdmin = $this->auth->isSuperAdmin();
    }

    public function article()
    {  //   文章统计
        $this->searchFields = 'id,name';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list=$this->model
                ->alias("a")
                ->field('a.channel_id,m.id,a.publishtime,m.name,m.list_type,sum(a.views) as views 
                ,sum(a.comments) as comments,sum(a.likes) as likes,count(a.id) as total')
                ->join("app_cms_channel m",'a.channel_id=m.id','left')
                ->group('a.channel_id')
                ->where($where)
                ->where("a.deletetime = 0 AND a.status='normal'")
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            $total = count($list);
            $total=$this->model
                ->alias("a")
                ->join("app_cms_channel m",'a.channel_id=m.id','left')
                ->where($where)
                ->where("a.deletetime = 0 AND a.status='normal'")
                ->group('a.channel_id')
                ->count();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function user_list(){
        $this->request->filter(['strip_tags', 'trim']);
        $this->searchFields = 'username,nickname';
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $s_id=input('s_id');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('admin')
                ->alias('a')
                ->field('a.*,b.group_id,s.*')
                ->join('auth_group_access b','a.id=b.uid','left')
                ->join('school_bind s','a.user_id=s.user_id','left')
                ->where($where)
                ->where("a.s_id=".$s_id." and s.user_id !='' and s.status='1' ")
                ->order('is_main desc,a.id desc,s.is_del asc')
                ->paginate($limit);
            $sql = DB::name('admin')->getLastSql();
            $result = array("total" => $list->total(), "rows" => $list->items(),'sql'=>$sql);
            return json($result);
        }
        return $this->view->fetch();
    }


    public function check_group($ids){
        if ($this->request->isAjax()) {
            $type=input('type');
            if ($type=='13'){
                $con['group_id']=14;
            }else{
                $con['group_id']=13;
            }
            $res=DB::name('ca_auth_group_access')->where(['uid'=>$ids])->update($con);
            if ($res){
                return['code'=>1,'msg'=>'更改成功！'];
            }else{
                return['code'=>0,'msg'=>'更改失败！'];
            }
        }
    }

    public function change_status(){
        $data=input('');
        if (empty($data['s_id'])){
            $this->error(__('未知'));
        }
        if($data['type']=='1'){
           $result=DB::name('admin')->where(['s_id'=>$data['s_id'],'type'=>'1'])->update(['status'=>'hidden']);
        }else{
            $result=DB::name('admin')->where(['s_id'=>$data['s_id'],'type'=>'1'])->update(['status'=>'normal']);
        }
        if ($result){
            $this->success();
        }
    }
    public function get_code(){ //二维码生成
        if ($this->request->isAjax()) {
            $data=input('');
            if($data['code_type'] == 1){
                $url="https://tool.gkzzd.cn/index/index/getwxacodeun2";
            }else{
                $url="https://tool.gkzzd.cn/partner/index/getwxacodeun2";
            }

// 传参，以数组方式
//            $data['url']="/pages/schoolbus/schoolbus_index";
            $params = ["param"=>$data['param'], "url"=>$data['url'], "file_name"=> $data['file_name']];
            $res=$this->post($url,$params);
            $res=json_decode($res,true);
            $this->success("success", null, $res);
        }
        return $this->view->fetch();
    }

    public function get_url(){
        $data=input('');
        $url="http://tool.gkzzd.cn/index/index/getXcxLink";
// 传参，以数组方式
        $params = ["path"=>urlencode($data['path'])];
        $headers = array('Content-Type: application/x-www-form-urlencoded');
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        $res=json_decode($result,true);
        $this->success("success", null, $res);
    }

    public function get_code2(){ //二维码生成
        if ($this->request->isAjax()) {
            $data=input('');
            $url="https://tool.gkzzd.cn/index/index/getwxacodeun2";
// 传参，以数组方式
//            $data['url']="/pages/schoolbus/schoolbus_index";
            $params = ["param"=>'a=1', "url"=>$data['url'], "file_name"=>"path".time()];
            $res=$this->post($url,$params);
            $res=json_decode($res,true);
            if ($res)DB::name('zd_path')->where(['id'=>$data['ids']])->update(['ewm_url'=>$res['image_url']]);
            $this->success("success", null, $res);
        }
        return $this->view->fetch();
    }

    public function path_list(){
        $this->searchFields = 'id,name';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('zd_path')
                ->where($where)
                ->where(['is_del'=>0])
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function hot_today (){ //今日热门
        $this->searchFields = 'title';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $Archives = DB::name('cms_archives');
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $time=strtotime(date("Y-m-d ",time()));
            $end_time=$time+86400;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $Archives
                ->alias('a')
                ->field('a.province,a.likes,a.type,a.id,a.channel_id,a.channel_ids,b.name,a.special_ids,m.nickname,a.title,a.flag,a.views,a.comments,a.publishtime,a.school_id')
                ->join('cms_channel b', 'a.channel_id=b.id', 'left')
                ->join('admin m', 'a.admin_id=m.id', 'left')
                ->where("a.deletetime = 0 AND a.status='normal' AND a.model_id=2  AND a.publishtime>=".$time." AND a.publishtime<".$end_time."")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => 15, "rows" => $list->items());
            return json($result);
        }
//        $res=DB::name('cms_channel')->field('id,name')->where(['type'=>'list','list_type'=>2,'status'=>'normal'])->select();
//        $this->assign("channel_list",$res);
//
//        $c=array_combine($fname,$age);
//       dump(json_encode($res));exit;
        return $this->view->fetch();
    }

    public function hot_article(){  //热门文章
        $this->searchFields = 'title';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $Archives = DB::name('cms_archives');
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $Archives
                ->where($where)
                ->where("deletetime = 0 AND status='normal' AND model_id=2 ")
                ->limit(100)
                ->count();

            $list = $Archives
                ->alias('a')
                ->field('a.province,a.likes,a.type,a.id,a.channel_id,a.channel_ids,b.name,a.special_ids,m.nickname,a.title,a.flag,a.views,a.comments,a.publishtime,a.school_id')
                ->join('cms_channel b', 'a.channel_id=b.id', 'left')
                ->join('admin m', 'a.admin_id=m.id', 'left')
                ->where("a.deletetime = 0 AND a.status='normal' AND a.model_id=2 ")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => 25, "rows" => $list->items());
            return json($result);
        }
//        $res=DB::name('cms_channel')->field('id,name')->where(['type'=>'list','list_type'=>2,'status'=>'normal'])->select();
//        $this->assign("channel_list",$res);
//
//        $c=array_combine($fname,$age);
//       dump(json_encode($res));exit;
        return $this->view->fetch();
    }

    public function special(){ //专题统计
        $this->searchFields = 'a.title,a.province';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list=DB::name("cms_special")
                ->alias("a")
                ->field('a.id,a.title,a.admin_id,d.nickname,a.image,a.createtime,a.province,a.views  
                ,sum(b.views) as archives_views,count(m.id) as total_archives')
                ->join("app_cms_archives_special m",'m.special_id=a.id','left')
                ->join("app_cms_archives b",'b.id=m.archives_id','left')
                ->join("app_admin d",'d.id=a.admin_id','left')
                ->group('a.id')
                ->where($where)
                ->where("b.deletetime = 0 AND a.status='normal' AND b.status='normal'")
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($list);exit;
            $total = DB::name("cms_special")
                ->alias("a")
                ->group('a.id')
                ->where($where)
                ->where("a.status='normal'")
                ->count();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function post($url, $data) {

        //初使化init方法
        $ch = curl_init();
        //指定URL
        curl_setopt($ch, CURLOPT_URL, $url);
        //设定请求后返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //声明使用POST方式来进行发送
        curl_setopt($ch, CURLOPT_POST, 1);
        //发送什么数据呢
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //忽略证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //忽略header头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //发送请求
        $output = curl_exec($ch);
        //关闭curl
        curl_close($ch);
        //返回数据
        return $output;
    }
//    private function post($url, $data)
//    {
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_POST, true);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
////        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_URL, $url);
//        $ret = curl_exec($ch);
//        header("Content-type: text/html; charset=utf-8");
//        curl_close($ch);
//        return $ret;
//
//    }
    public function module_data(){  //小程序模块访问统计汇总
        $this->searchFields = 'name';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('module_path_clicks')
                ->alias('a')
                ->field('a.time,m.name,a.page_path,sum(a.page_visit_uv) as page_visit_uv ,sum(a.page_visit_pv) 
                as page_visit_pv,sum(a.page_share_pv) as page_share_pv,sum(a.page_share_uv) as page_share_uv')
                ->join('zd_path m','a.page_path=m.xcx_url','left')
                ->where($where)
                ->group('page_path')
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $date=date('Y-m-d',time()-86439);
        $this->assign('date',$date);
        return $this->view->fetch();
    }

    public function module_data_daily(){
        $this->searchFields = 'name';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $url=input('url');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('module_path_clicks')
                ->alias('a')
                ->field('m.name,a.*')
                ->join('zd_path m','a.page_path=m.xcx_url','left')
                ->where($where)
                ->where("a.page_path='".$url."'")
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $date=date('Y-m-d',time()-86439);
        $this->assign('date',$date);
        return $this->view->fetch();
    }

    public function module_name(){
        $url=input('url');
        if (empty($url)) return '未知错误';
        if ($this->request->isAjax()) {
            $name=input('name');
            $url=input('url');
            if (!DB::name('zd_path')->where(['xcx_url'=>$url,'is_del'=>0])->update(['name'=>$name])){
                DB::name('zd_path')->insert(['xcx_url'=>$url,'name'=>$name]);
            }
        }
        $res=DB::name('zd_path')->field('xcx_url,name')->where(['xcx_url'=>$url,'is_del'=>0])->find();
        $this->assign('res',$res);
        $this->assign('url',$url);
        return $this->view->fetch();
    }

    public function module_date_clicks(){ //每日汇总
        $this->searchFields = 'name';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('module_path_clicks')
                ->alias('a')
                ->field('FROM_UNIXTIME(time,"%Y-%m-%d") as time,sum(a.page_visit_uv) as page_visit_uv,sum(a.page_visit_pv) as page_visit_pv,sum(a.page_share_uv) as page_share_uv,sum(a.page_share_pv) as page_share_pv')
                ->where($where)
                ->group('a.time')
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function module_today_list(){ //今日访问
        $this->searchFields = 'name';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $time=strtotime(input('time'));
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('module_path_clicks')
                ->alias('a')
                ->field('m.name,a.*')
                ->join('zd_path m','a.page_path=m.xcx_url','left')
                ->where($where)
                ->where("a.time='".$time."'")
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $date=date('Y-m-d',time()-86439);
        $this->assign('date',$date);
        return $this->view->fetch();
    }

    public function icon(){
        $like=input('get.school');
        $pid=input('get.pid')?input('get.pid'):3;
        $data=DB::name('icon')
            ->field('id,image_url,xcx_url,h5_url,type,province,path_id')
            ->where(['province'=>$pid])
            ->order('sort asc')
            ->select();
//        $path=DB::name('zd_path')->field('id,name')->where("is_del=0 and icon_url!=''")->select();
//        $this->assign('path',$path);
        $province=get_pro();
        $this->assign('province',$province);
        $this->assign('pid',$pid);
        $this->assign('data',$data);
        return $this->view->fetch();
    }


    public function do_icon(){
       $data=input('');
       if (empty($data['pid'])){
           $this->error(__('省份有误'));
       }
        DB::name('icon')->where(['province'=>$data['pid']])->delete();
       $a=0;
       $con=[];
       for ($i=1;$i<11;$i++){
            $res=$this->get_icon_mes($data["path".$i.""]);
            $con[$a]['province']=$data['pid'];
            $con[$a]['update_time']=time();
            $con[$a]['admin_id']=session('admin.id');
            $con[$a]['sort']=$i;
            $con[$a]['path_id']=$data["path".$i.""];
           $con[$a]['path_name']=$data["path".$i."_text"];
            if ($i<6){
                $con[$a]['type']=1;
            }else{
                $con[$a]['type']=2;
            }
            $con[$a]['xcx_url']=$res['xcx_url'];
            $con[$a]['h5_url']=$res['h5_url'];
            $con[$a]['image_url']=$res['icon_url'];
            $a++;
       }
       $result=DB::name('icon')->insertAll($con);
       if ($result){
           $this->success();
       }
    }
    public function get_path()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $datalist = [];

        $total = DB::name("zd_path")->where($where)->where("is_del=0 and icon_url!=''")->count();
//        dump($this->model->getLastSql());exit;
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = DB::name("zd_path")->field('id,name')->where("is_del=0 and icon_url!=''")->where($where)
                ->page($page, $pagesize)
                ->select();

        }


        return json(['list' => $datalist, 'total' => $total]);
    }

    public function get_icon_mes($id){
        $res=DB::name('zd_path')->field("xcx_url,h5_url,icon_url")->where(['id'=>$id])->find();
        return $res;
    }




    public function push_school(){ //推送管理
        $this->searchFields = 'name,phone,duty';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $model=DB::name('school_bind');
            $total = $model
                ->where($where)
                ->where(['is_del'=>0,'status'=>'1'])
                ->count();
            $list = $model
                ->alias('a')
                ->field("a.*,b.`from`,c.time,c.msg")
                ->join('admin b','b.username=a.phone','left')
                ->join('wx_template_log c','c.b_id=a.id','left')
                ->where(['a.is_del'=>0,'a.status'=>'1'])
                ->where($where)
                ->group('a.id')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    public function zxh_list(){ //咨询会登记列表
        $this->searchFields = 'name,phone';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $con = [];
            $session_id=input('session_id');
            if ($session_id)$con['session_id']=$session_id;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,2);
            $model=DB::name('zd_user_zxh');
            $total = $model
                ->alias('a')
                ->where($con)
                ->where($where)
                ->where(['is_del'=>0])
                ->count();
            $list = $model
                ->alias('a')
                ->field('a.*,b.session_name,b.begin_time,b.hold_time')
                ->join('zd_zxh_session b','a.session_id=b.id','left')
                ->where(['a.is_del'=>0])
                ->where($con)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $sql = $model->getLastSql();
            $result = array("total" => $total, "rows" => $list,"sql" => $sql);
            return json($result);
        }
        return $this->view->fetch();
    }


    public function complain(){
        $this->searchFields = 'name,phone';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $model=DB::name('user_feedback');
            $total = $model
                ->where($where)
                ->count();
            $list = $model
                ->alias('a')
                ->field('a.*,b.nick_name,b.phone,b.head_image')
                ->join('zd_user b','a.user_id=b.user_id','left')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }



    public function page_log(){
        $this->searchFields = 'user_id';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $model=DB::name('zd_user_log_page');
            $list = $model
                ->alias('a')
                ->field('a.create_time,a.page,FROM_UNIXTIME(create_time,"%Y-%m-%d") as time,
               count(user_id) as total,count(DISTINCT user_id) as num')
                ->where($where)
                ->group('FROM_UNIXTIME(create_time,"%Y-%m-%d"),a.page')
                ->order($sort, $order)
                ->paginate($limit);
//            dump($list);exit;
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    public function school_data(){ //院校合作统计
        $this->searchFields = 'b.name';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $have=DB::name('zd_province_target')->where("m_id=".session('admin.id')."")->count();
            $con=[];
            if ($have>0){
                $con['a.m_id']=session('admin.id');
            }
            $list = DB::name('school_z')
                ->alias('s')
                ->field('s.province_id,c.id,count(*) as nums,sum(s.sign) as sign,a.p_target,c.name,p.nickname,sum(t.follows_cj+t.follows) as follows_all,
                k.follows,sum(t.views) as views,sum(t.enrolls) as enrolls,sum(t.users) as users,sum(t.datas) as datas,
                 sum(m.all_question_num) all_question_num,sum(m.answer_num) answer_num,sum(t.visits) as visits')
                ->join('school_z_statistics t','t.id=s.id','left')
                ->join('(select count(*) as follows,school_id from app_zd_user_school_follow 
                where create_time>1640966400 and is_del=0 group by school_id) k','k.school_id=s.id','left')
                ->join("(select status,id_a,count(id) as all_question_num, sum(case when status='1' then 1 else 0 end) as question_num ,sum(case when status='2'  
then 1 else 0 end) as answer_num from app_zd_user_school_question where is_del=0  group by id_a) m",'m.id_a=s.id','left')
                ->join('province c','c.id=s.province_id','left')
                ->join('zd_province_target a','c.id=a.pro_id','left')
                ->join('admin p','p.id=a.m_id','left')
                ->where($con)
                ->where($where)
                ->group('s.province_id')
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function school_data_edit($ids=null){
        if ($this->request->isPost()){
            $data=input('');
            if(!DB::name('zd_province_target')->where(['pro_id'=>$ids])->update($data['row'])){
                $data['row']['pro_id']=$ids;
                DB::name('zd_province_target')->insert($data['row']);
            }
            $this->success();
        }
        $res=DB::name('province')
            ->alias('a')
            ->field('c.*,a.name,a.id')
            ->join('zd_province_target c','a.id=c.pro_id','left')
            ->where(['a.id'=>$ids])
            ->find();
        $this->assign('res',$res);
        return $this->view->fetch();
    }



    public function pro_school_list($ids=null){
        $this->searchFields = 'a.id,a.school,a.former_name,a.alias_name';
        $pid=$ids;
        if (empty($pid))return '未知错误';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $con['province_id']=$pid;
            $con['a.is_lock']=0;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('school_z')
                ->alias('a')
                ->field('a.sign,a.target,t.enrolls,t.visits,t.datas,t.comments,t.users, a.batch,a.is_985,a.is_211,a.is_syl,a.genre,question_num as question_num_all,b.answer_num as answer_num_all,b.all_question_num all_question_num_all,(t.follows_cj+t.follows) as follows_all,a.id,a.school,t.article_nums,t.follows,t.enrolls_cj as enroll,t.follows_cj ,
                a.is_red,a.is_lock,b.all_question_num,b.answer_num,b.question_num')
                ->join('school_z_statistics t','t.id=a.id','left')
                ->join("(select status,id_a,count(id) as all_question_num, sum(case when status='1' then 1 else 0 end) as question_num ,sum(case when status='2'  
then 1 else 0 end) as answer_num from app_zd_user_school_question where is_del=0  group by id_a) b",'b.id_a=a.id','left')
                ->where($where)
                ->where($con)
                ->group('a.id')
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
//        $this->assign('pid',$pid);
        return $this->view->fetch();

    }

    public function school_target($ids=null){
        if ($this->request->isPost()){
            $data=input('');
            DB::name('school_z') ->where(['id'=>$ids])->update($data['row']);
            $this->success();
        }
        $res=DB::name('school_z')
            ->alias('a')
            ->field('target,sign')
            ->where(['id'=>$ids])
            ->find();
        $this->assign('res',$res);
        return $this->view->fetch();
    }



    public function middle_school_data(){ //中学院校
        $this->searchFields = 'province';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('zd_middle_school')
                ->alias('s')
                ->field('s.province,s.id,count(*) as nums,sum(s.sign) as sign,sum(s.register_num) as register_num,sum(s.student_2022) as student_num')
//                ->join('(SELECT student_num,school_id FROM
//                app_zd_middle_school_student order by
//                year desc limit 1) a','a.school_id=s.id','left')
                ->where($where)
                ->group('s.province')
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function middle_school_data_list(){
        $this->searchFields = 's.school';
        $name=input('')['name'];
        if (empty($name))return '未知错误';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $con['s.province']=$name;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('zd_middle_school')
                ->alias('s')
                ->field('s.id,s.school,s.province,s.sign,s.register_num,s.student_2022 as student_num')
//                ->join('(SELECT student_num,school_id FROM
//                app_zd_middle_school_student order by
//                year desc limit 1) a','a.school_id=s.id','left')
                ->where($con)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();

    }
    public function middle_school_data_edit($ids=null){
        if ($this->request->isPost()){
            $data=input('');
            if ($data['row']['sign']==1){
                $data['row']['status']='1';
            }else{
                $data['row']['status']='0';
            }
            $relust=DB::name('zd_middle_school')
                ->where(['id'=>$ids])
                ->update($data['row']);
            if ($relust)$this->success();
        }
        $res=DB::name('zd_middle_school')
            ->where(['id'=>$ids])
            ->find();
        $this->assign('res',$res);
        return $this->view->fetch();
    }


    public function middle_admin(){
        $this->searchFields = 'province';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('zd_middle_school')
                ->alias('s')
                ->field('s.province,s.id,count(*) as nums,sum(s.sign) as sign,sum(s.register_num) as register_num,sum(s.student_2022) as student_num')
//                ->join('(SELECT student_num,school_id FROM
//                app_zd_middle_school_student order by
//                year desc limit 1) a','a.school_id=s.id','left')
                ->where($where)
                ->group('s.province')
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function middle_school_admin_list(){
        $this->searchFields = 's.school';
        $name=input('')['name'];
        if (empty($name))return '未知错误';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $con['s.province']=$name;
//            $con['b.is_del']=0;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('zd_middle_school')
                ->alias('s')
                ->field('b.name,b.phone,s.id,s.school,s.province,s.sign,s.register_num,s.student_2022 as student_num')
                ->join('(select m_id,name,phone from app_zd_middle_admin_member where is_del=0 limit 1 ) b','b.m_id=s.id','left')
//                ->join('(SELECT student_num,school_id FROM
//                app_zd_middle_school_student order by
//                year desc limit 1) a','a.school_id=s.id','left')
                ->where($con)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();

    }

    public function middle_school_admin_edit($ids=null){
        if ($this->request->isPost()){
            $data=input('');
            $data['row']['if_send_wc'] = 0;
            if(isset($data['row']['if_send_wc'])){
                $data['row']['if_send_wc'] = 1;
            }
            if ($data['row']['sign']==1){
                $data['row']['status']='1';
            }else{
                $data['row']['status']='0';
                $data['row']['if_send_wc']=0;
                $data['row']['vip_num']=0;
            }
            $relust=DB::name('zd_middle_school')
                ->where(['id'=>$ids])
                ->update($data['row']);
            $res=DB::name('zd_middle_admin_member')->where(['m_id'=>$ids])->update(['is_del'=>1]);
            $data['member']['m_id']=$ids;
            DB::name('zd_middle_admin_member')->where(['m_id'=>$ids])->insert($data['member']);
            if ($relust)$this->success();
        }
        $res=DB::name('zd_middle_school')
            ->alias('a')
            ->field('a.*,b.*')
            ->join('(select * from app_zd_middle_admin_member where is_del=0 limit 1 ) b','b.m_id=a.id','left')
            ->where(['a.id'=>$ids])
            ->find();
        $count =DB::name('zd_user_give')->where(['send_type'=>2,'school_id'=>$ids])->count('id');
        $arr = [
            1=>'五查会员',
//            2=>'模拟填报',
        ];
        $this->assign('res',$res);
        $this->assign('arr',$arr);
        $this->assign('send_num',$count);
        return $this->view->fetch();
    }


    public function middle_talk($ids=null){
        $this->searchFields = 's.school';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = DB::name('zd_middle_talk')
                ->where($where)
                ->where(['school_id'=>$ids])
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    public function update_access_token(){ //刷新token
        if ($this->request->isAjax()) {
            $url="https://tool.gkzzd.cn/index/index/GetAccessTokenNew";
            $return = $this->curlGet($url);
            $this->success('更新成功',$return);
        }
        return $this->view->fetch();
    }

public  function curlGet($url = '', $options = array())
{
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    return $response;
}

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    public function buildparams($searchfields = null, $relationSearch = null,$type=1)
    {

        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        if(request()->controller()=='Extend.datas'){
            $sort=$this->request->get("sort");
        }else{
            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        }


//        dump($this->model->getPk());exit;
//        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
//        $sort='id';
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码

        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        if (strtolower(request()->action())=='wx_article'){
            if (isset($filter['status'])){
                if ($filter['status']=='3')$filter['status']='1';
            }
        }elseif (strtolower(request()->controller())=='extend.users'){
            if (isset($filter['all_vip_type'])){
                if ($filter['all_vip_type']=='1')unset($filter['all_vip_type']);
            }
//            dump($filter['all_type']);exit;

        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';

        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        if($type == 1){
            $where = function ($query) use ($where, $alias, $bind, &$model) {
                if (!empty($model)) {
                    $model->alias($alias);
                    $model->bind($bind);
                }
                foreach ($where as $k => $v) {
                    if (is_array($v)) {
                        call_user_func_array([$query, 'where'], $v);
                    } else {
                        $query->where($v);
                    }
                }
            };
        }else if($type == 2){
            $where = function ($query) use ($where, $alias, $bind, &$model) {
                if (!empty($model)) {
                    $model->alias($alias);
                    $model->bind($bind);
                }
                foreach ($where as $k => $v) {
                    if($v[0] == 'create_time'){
                        $v[0] = 'a.create_time';
                    }
                    if (is_array($v)) {
                        call_user_func_array([$query, 'where'], $v);
                    } else {
                        $query->where($v);
                    }
                }
            };
        }

        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }
}
